package zoo.order.controller;

import java.util.HashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import zoo.member.dao.MemberDao;
import zoo.member.domain.MemberCommand;
import zoo.order.dao.OrderDao;
import zoo.order.domain.OrderCommand;
import zoo.order.validator.OrderValidator;

@Controller
public class OrderBuyController {
	
	@Autowired
	private MemberDao dao;
	
	@Autowired
	private OrderDao orDao;
	
	private String formViewName = "order_product";
	
	
	@ModelAttribute("orCom")
	public OrderCommand formBacking() {
		return new OrderCommand();
	}
	
	@RequestMapping(value="/main/order.do", method=RequestMethod.GET)
	public ModelAndView submit(@ModelAttribute("orCom") OrderCommand orCommand,
								@ModelAttribute("command") MemberCommand member
								){
			
		member = dao.getMember(orCommand.getUserid());
		
		System.out.println(member);
				
		ModelAndView mav = new ModelAndView();
		mav.setViewName(formViewName);
		mav.addObject("orCom",orCommand);
		mav.addObject("command",member);
		return mav;
		
	}
	
	@RequestMapping(value="/main/order.do", method=RequestMethod.POST)
	public ModelAndView form(@ModelAttribute("orCom") OrderCommand orCommand,
							 @ModelAttribute("command") MemberCommand member
			){
		orDao.insertOrder(orCommand);
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("userid", orCommand.getUserid());
		map.put("or_finaltotal", orCommand.getOr_finaltotal());
		
		//차감 
		dao.chargePoint(map);
		
		//회원 남은 포인트 
		MemberCommand member2 = dao.getMember(orCommand.getUserid());
		
		System.out.println("userid = "+orCommand.getUserid()+"or_finaltotal = "+orCommand.getOr_finaltotal());
				
		ModelAndView mav = new ModelAndView();
		mav.setViewName("ordermember");
		mav.addObject("orCom",orCommand);
		mav.addObject("member2",member2);
		return mav;
		
	}
}
